#!/bin/sh

add_chain() {
  /sbin/iptables -N $1
  /sbin/iptables -A $1 -p $2 --dport $3 -j ACCEPT
  /sbin/iptables -A in_mod -j $1
  /sbin/iptables -t nat -N $1
  /sbin/iptables -t nat -A $1 -p $2 --dport $3 -j ACCEPT
  /sbin/iptables -t nat -A pre_mod -j $1
}

del_chain() {
  /sbin/iptables -D in_mod -j $1
  /sbin/iptables -F $1
  /sbin/iptables -X $1
  /sbin/iptables -t nat -D pre_mod -j $1
  /sbin/iptables -t nat -F $1
  /sbin/iptables -t nat -X $1
}

case "$1" in
  start|restart)
	. /opt/httpAuth/etc/settings
	if [ "$1" = "restart" ]; then
	    echo -n "Restarting module httpAuth: "
	    killall httpAuthd 2> /dev/null
        del_chain mod_httpauth 2> /dev/null
	else
	    echo -n "Starting module httpAuth: "
	fi
	if [ "$MOD_HTTPAUTH_ENABLED" != "1" ]; then
	    echo "skipped"
	    exit 0
	fi
        add_chain mod_httpauth tcp $MOD_HTTPAUTH_LPORT 2> /dev/null
	/opt/httpAuth/bin/httpAuthd &
	RETVAL=$?
	if [ $RETVAL = 0 ]; then echo "done"; else echo "failed"; fi
	exit $RETVAL
	;;
  stop)
	echo -n "Stopping module httpAuth: "
	killall httpAuthd 2> /dev/null
        del_chain mod_httpauth 2> /dev/null
	RETVAL=$?
	if [ $RETVAL = 0 ]; then echo "done"; else echo "failed"; fi
	exit $RETVAL
	;;
  status)
	echo -n "Module httpAuth is "
	killall -0 tcp2rtud 2> /dev/null
	RETVAL=$?
	if [ $RETVAL = 0 ]; then echo "running"; else echo "stopped"; fi
	exit $RETVAL
	;;
  defaults)
	cp /opt/httpAuth/etc/defaults /opt/httpAuth/etc/settings 2> /dev/null
	;;
  *)
	echo "Usage: $0 {start|stop|restart|status|defaults}"
	exit 1
esac
